package com.example.newhabitclock.CalendarView

import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.example.newhabitclock.MainViewModel
import com.example.newhabitclock.R
import com.example.newhabitclock.databinding.FragmentCalendarHostBinding

//在fragment_calendar_item的弗雷容器中设置viewPager2的适配器
class CalendarHostFragment : Fragment() {
    private lateinit var binding: FragmentCalendarHostBinding
    private val viewModel: MainViewModel by activityViewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentCalendarHostBinding.inflate(layoutInflater)
        return binding.root
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 限制只保留当前页面，减少内存占用
        binding.viewPager2.offscreenPageLimit = 2

        //获取习惯列表并绑定适配器
        viewModel.allHabits.observe(viewLifecycleOwner) { habits ->
            binding.viewPager2.adapter = CalendarPagerAdapter(this, habits)
        }
    }

}